package com.hzg.lanya.frame;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONObject;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class utils {

    /**
     * 获取ip地址
     * @return
     */
    public static String getIP() {

        String hostIp = null;
        try {
            Enumeration nis = NetworkInterface.getNetworkInterfaces();
            InetAddress ia = null;
            while (nis.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface) nis.nextElement();
                Enumeration<InetAddress> ias = ni.getInetAddresses();
                while (ias.hasMoreElements()) {
                    ia = ias.nextElement();
                    if (ia instanceof Inet6Address) {
                        continue;// skip ipv6
                    }
                    String ip = ia.getHostAddress();
                    if (!"127.0.0.1".equals(ip)) {
                        hostIp = ia.getHostAddress();
                        break;
                    }
                }
            }
        } catch (SocketException e) {
            Log.i("yao", "SocketException");
            e.printStackTrace();
        }
        return hostIp;
    }

    /**
     * 获取版本信息
     * @return  s[0]--版本名称   s[1]--版本号
     */
    public static String[] getBanBenXinXi(Context context){
        String versionName="";
        String versionCode="";
        String[] s=new String[2];
        try {
            PackageManager mPackageManager=context.getPackageManager();
            PackageInfo pinfo=mPackageManager.getPackageInfo(context.getPackageName(), PackageManager.GET_CONFIGURATIONS);
            versionName=pinfo.versionName;// 1.0.1
            versionCode=""+pinfo.versionCode;// 1
            s[0]=versionName;
            s[1]=versionCode;

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return s;
    }

    /**
     *  弹出提示框
     * @param context
     */
    public static void prompt(Context context, String message, String titel){

        TextView textView=null;
        try {
//            textView=new TextView(context);
//            textView.setTextColor(Color.BLACK);//黑色
//            textView.setText(titel);//设置标题
//            textView.setTextSize(25);
//            textView.setGravity(Gravity.CENTER);//居中
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            //builder.setCustomTitle(textView)
            builder.setTitle(titel)
                    .setMessage(message)
                    .setNeutralButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (dialog!=null){
                                dialog.dismiss();
                            }

                        }
                    });
            AlertDialog dialog = builder.create();//创建
            dialog.show();
//            WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
//            params.width = 600;
//                params.height = 500;
//                params.gravity = Gravity.CENTER;
//                //alpha在0.0f到1.0f之间。1.0完全不透明，0.0f完全透明，自身不可见。
//                params.alpha=1.0f;
//                // 这个是设置activity的亮度的dimAmount在0.0f和1.0f之间，0.0f完全不暗，即背景是可见的 ，1.0f时候，背景全部变黑暗。
//                params.dimAmount = 0.5f;
//                dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));//背景透明
//                // 设置对话框的布局参数为居中
//            dialog.getWindow().setAttributes(params);

        }catch (Exception e){}
    }

    public static final int MODE_PRIVATE = 0;
    //写入数据
    public static void setSharedPreferences(Context context, String name, HashMap<String, Object> map){
        SharedPreferences preferences = context.getSharedPreferences(name, MODE_PRIVATE);
        //2,让SharedPreferences处于可编辑状态
        SharedPreferences.Editor editor = preferences.edit();
        //3,储存数据,类似于map
        Iterator iter = map.entrySet().iterator();
        while (iter.hasNext()) { //遍历map对象
            Map.Entry entry = (Map.Entry) iter.next();
            String key = (String) entry.getKey();
            String val = (String)entry.getValue();
            editor.putString(key, val);
        }
        //4,提交
        editor.commit();
    }
    //获取数据
    public static String getSharedPreferences(Context context, String name, String key) {
        //得到数据
        //1,得到SharedPreferences对象
        SharedPreferences preferences = context.getSharedPreferences(name, MODE_PRIVATE);
        //2,取出数据
        String v = preferences.getString(key, "");
        return v;
    }

    //写入数据
    public static void setSharedPreferences(Context context, String key, ArrayList<HashMap<String, Object>> list){
        SharedPreferences preferences = context.getSharedPreferences("CSJL_XML", MODE_PRIVATE);
        //2,让SharedPreferences处于可编辑状态
        SharedPreferences.Editor editor = preferences.edit();

        JSONArray jsonArray=new JSONArray();
        for (int i=0;i<list.size();i++){
            HashMap<String, Object> map=(HashMap<String, Object>)list.get(i);
            JSONObject jsonObject=new JSONObject();
            try {
                jsonObject.put("bh",""+map.get("bh"));
                jsonObject.put("rq",""+map.get("rq"));
                jsonObject.put("sj",""+map.get("sj"));
                jsonObject.put("dy",""+map.get("dy"));
                jsonObject.put("dl",""+map.get("dl"));
                jsonObject.put("dz",""+map.get("dz"));
                jsonArray.put(jsonObject);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        editor.putString(key, ""+jsonArray);
        //4,提交
        editor.commit();
    }
    //获取数据
    public static ArrayList<HashMap<String, Object>> getSharedPreferences(Context context, String key) {
        ArrayList<HashMap<String, Object>> list=new ArrayList<HashMap<String, Object>>();
        //得到数据
        //1,得到SharedPreferences对象
        SharedPreferences preferences = context.getSharedPreferences("CSJL_XML", MODE_PRIVATE);
        //2,取出数据
        String v = preferences.getString(key, null);
        if (v==null || v.length()<5){
            return list;
        }else {
            try {
                JSONArray jsonArray=new JSONArray(v);
                for (int i=0;i<jsonArray.length();i++){
                    JSONObject jsonObject=jsonArray.getJSONObject(i);
                    HashMap<String, Object> map=new HashMap<String, Object>();
                    map.put("bh",""+jsonObject.get("bh"));
                    map.put("rq",""+jsonObject.get("rq"));
                    map.put("sj",""+jsonObject.get("sj"));
                    map.put("dl",""+jsonObject.get("dl"));
                    map.put("dy",""+jsonObject.get("dy"));
                    map.put("dz",""+jsonObject.get("dz"));
                    list.add(map);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }



        return list;
    }





    public static void  toastError(Context context, String code, String error){
        Toast.makeText(context, "code: " + code + "error:" + error, Toast.LENGTH_SHORT).show();
    }

    public static ProgressDialog p;
    /**
     * 圆形加载框
     * @param mContext
     * @param Title
     * @param Message
     * @param Cancelable
     * @return
     */
    public static ProgressDialog setProgressDialog(Context mContext, String Title, String Message, boolean Cancelable){
        if (p==null)
            p=new ProgressDialog(mContext);
        p.setTitle(Title);
        p.setMessage(Message);
        p.setCancelable(Cancelable);
        //p.show();
        return p;
    }


    //ascii 转字符串
    public static String asciiToString(String hexs){
        String str="";
        try {
            for (int i=2;i<=hexs.length();i++){
                if (i%2==0){
                    str=str+ascii(hexs.substring(i-2,i));
                }
            }
        }catch (Exception e){
        }

        return str;
    }
    private static String ascii(String hex){
//        HashMap<String,String> map=new HashMap<String,String>();
//        map.put("30","0");
        String str="";
        switch (hex){
            case "30":str="0";break;
            case "31":str="1";break;
            case "32":str="2";break;
            case "33":str="3";break;
            case "34":str="4";break;
            case "35":str="5";break;
            case "36":str="6";break;
            case "37":str="7";break;
            case "38":str="8";break;
            case "39":str="9";break;
            case "41":str="A";break;
            case "42":str="B";break;
            case "43":str="C";break;
            case "44":str="D";break;
            case "45":str="E";break;
            case "46":str="F";break;
            case "47":str="G";break;
            case "48":str="H";break;
            case "49":str="I";break;
            case "4A":str="J";break;
            case "4B":str="K";break;
            case "4C":str="L";break;
            case "4D":str="M";break;
            case "4E":str="N";break;
            case "4F":str="O";break;
            case "50":str="P";break;
            case "51":str="Q";break;
            case "52":str="R";break;
            case "53":str="S";break;
            case "54":str="T";break;
            case "55":str="U";break;
            case "56":str="V";break;
            case "57":str="W";break;
            case "58":str="X";break;
            case "59":str="Y";break;
            case "5A":str="Z";break;
            case "2D":str="-";break;
            case "61":str="a";break;
            case "62":str="b";break;
            case "63":str="c";break;
            case "64":str="d";break;
            case "65":str="e";break;
            case "66":str="f";break;
            case "67":str="g";break;
            case "68":str="h";break;
            case "69":str="i";break;
            case "6A":str="j";break;
            case "6B":str="k";break;
            case "6C":str="l";break;
            case "6D":str="m";break;
            case "6E":str="n";break;
            case "6F":str="o";break;
            case "70":str="p";break;
            case "71":str="q";break;
            case "72":str="r";break;
            case "73":str="s";break;
            case "74":str="t";break;
            case "75":str="u";break;
            case "76":str="v";break;
            case "77":str="w";break;
            case "78":str="x";break;
            case "79":str="y";break;
            case "7A":str="z";break;
            default:str="*";
        }
        return str;
    }

    public static String stringToAscii(String str){
        String s="";
        char[] strChar = str.toCharArray();
        for (char a:strChar){
            int value= Integer.valueOf(a);//97
            String hex=utils.intToHex(value);
            s=s+hex;
        }

        return s;
    }

    public static int hexToInt(String hex){
        int i=0;
        try {
            i = Integer.valueOf(hex,16);
        }catch (Exception e){
        }
        return i;
    }

    public static String intToHex(int i){
        String st = Integer.toHexString(i).toUpperCase();
        st = String.format("%5s",st);
        st= st.replaceAll(" ","0");
        //st=st.substring(st.length()-2,st.length());
        return st;
    }

    /**
     * 计算效验码
     * @param data
     * @return
     */
    public static String sum(String data){
        if (data.length()%2!=0)
            return "";
        int length=data.length();
        int sums=0;
        for (int i=2;i<=length;i++){
            if (i%2==0){
                String a=data.substring(i-2,i);
                Integer int1 = Integer.valueOf(a,16);
                sums=sums+int1;
            }
        }

        String st = Integer.toHexString(sums).toUpperCase();
        st = String.format("%5s",st);
        st= st.replaceAll(" ","0");
        st=st.substring(st.length()-2,st.length());
        return st;
    }


    /**
     * 转16进制发送
     * @param var0
     * @return
     */
    public static byte[] hexToByteArray(String var0) {
        if (var0 != null && var0.length() != 0) {
            if (var0.length() % 2 == 1) {
                var0 = "0" + var0;
            }

            String[] var1;
            byte[] var2 = new byte[(var1 = new String[var0.length() / 2]).length];

            for(int var3 = 0; var3 < var1.length; ++var3) {
                var1[var3] = var0.substring(2 * var3, 2 * (var3 + 1));
                var2[var3] = (byte)Integer.parseInt(var1[var3], 16);
            }

            return var2;
        } else {
            return null;
        }
    }

    /**
     * 16进制转string 接收
     * @param var0
     * @return
     */
    public static String byteArrayToHex(byte[] var0) {
        if (var0 != null && var0.length != 0) {
            StringBuilder var1 = new StringBuilder(var0.length);

            for(int var2 = 0; var2 < var0.length; ++var2) {
                var1.append(String.format("%02X", var0[var2]));
                if (var2 < var0.length - 1) {
                    var1.append(' ');
                }
            }

            return var1.toString();
        } else {
            return "";
        }
    }



}
